<template>
  <div @keyup.enter="getConData()">
    <el-form class="query-table-form" :inline="true">
      <el-form-item>
        <el-input v-model="params.customer_name" placeholder="主体名称查询" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="params.corp_name" placeholder="负责人查询" :clearable="true"></el-input>
      </el-form-item>
      <el-form-item>
        <select-address
          v-model="params.address_code"
          placeholder="地址查询"
          auto-top
          clearable
          @change="getConData()"
        ></select-address>
      </el-form-item>
      <el-form-item>
        <c-select
          :options="enumStatus"
          v-model="selectStatus"
          clearable
          placeholder="处理状态"
          @change="handleStatusChange"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" @click="getConData()">查询</el-button>
      </el-form-item>
      <el-form-item class="float-right">
        <el-button @click="handleFlow">
          <i class="fa fa-sitemap"></i>
          审批流程
        </el-button>
      </el-form-item>
    </el-form>
    <c-table border v-loading="loading" :columns="tableColumns" :data="tableData">
      <template v-slot:address="scope">
        <div class="text-truncate" :title="scope.row.address">{{ scope.row.address }}</div>
      </template>
      <template v-slot:itemStatus="scope">
        <span class="badge" :class="`badge-${scope.row.itemStatusStyle}`">
          {{ scope.row.itemStatusLabel }}
        </span>
      </template>
      <template v-slot:name="scope">
        <el-popover placement="top-start" title="项目经理" trigger="hover">
          <div>
            <div>{{ `A角： ${scope.row.res_a_name || '-'}；` }}</div>
            <div class="mb-2">{{ `电话： ${scope.row.res_a_phone || '-'}` }}</div>
            <div>{{ `B角： ${scope.row.res_b_name || '-'}；` }}</div>
            <div>{{ `电话： ${scope.row.res_b_phone || '-'}` }}</div>
          </div>
          <div slot="reference">
            <div class="status-label badge-info text-left w-100">
              <div>A角:{{ scope.row.res_a_name }}</div>
              <div>B角:{{ scope.row.res_b_name }}</div>
            </div>
          </div>
        </el-popover>
      </template>
    </c-table>
    <div class="query-pagination">
      <div></div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="totalCount"
        @current-change="getConData"
      ></el-pagination>
    </div>

    <el-dialog
      :visible.sync="reportVisible"
      :close-on-click-modal="false"
      append-to-body
      top="30px"
      width="80%"
    >
      <el-tabs v-model="active">
        <el-tab-pane label="项目信息" name="first">
          <info-view :related-data="relatedData"></info-view>
        </el-tab-pane>
        <el-tab-pane label="合同审批表">
          <contract-approve
            :query-id="queryId"
            :process-status="relatedData.process_status"
            view-mode
          ></contract-approve>
        </el-tab-pane>
        <el-tab-pane label="项目审批表">
          <investigate-approve-view
            :query-id="queryId"
            :process-status="relatedData.process_status"
          ></investigate-approve-view>
        </el-tab-pane>
        <el-tab-pane label="合同信息" name="contract">
          <contract-guard-view :query-id="queryId"></contract-guard-view>
        </el-tab-pane>
        <el-tab-pane label="担保意向函" name="letter" v-if="+relatedData.ele_letter_status > 0">
          <letter-view :query-id="queryId"></letter-view>
        </el-tab-pane>
        <el-tab-pane label="附件">
          <attach-view :queryId="queryId" :visible="reportVisible"></attach-view>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <attach-cmpt :visible.sync="attachVisible" :customer-related-id="attachRelatedId"></attach-cmpt>

    <contract-approve-dialog
      :visible.sync="editVisible"
      :query-id="editQueryId"
      :process-status="editProcess"
      @success="handleSuccess"
    ></contract-approve-dialog>

    <flow-dialog title="合同审批流程" :visible.sync="flowVisible" :flow-key="flowKey"></flow-dialog>
  </div>
</template>

<script>
import { enumGuatype, enumProjectResStatus, enumProcessStatus } from '@/credit/plugins/enumTown'
import { baseTableColumns } from '@/credit/views/province/mission/UnionNo'
import { getEntrustContract } from '@/credit/views/county/unionProvince/components/contractGuardMixins'
import { getFollow } from '@/credit/mixin/taskTableCountyUnionProvince'
import baseMixins from '@/credit/views/city/self/normal/mixins'

import SelectAddress from '@/components/select/SelectAddress'
import AttachView from '@/credit/components/AttachView'
import AttachCmpt from '@/credit/views/city/program/Attach'
import InvestigateApproveView from '@/credit/views/city/self/components/investApprove/Main'
import ContractApprove from '@/credit/views/city/self/components/contractApprove/Main'
import ContractApproveDialog from '@/credit/views/city/self/components/contractApprove/MainDialog'
import ContractGuardView from '@/credit/views/county/unionProvince/components/ContractGuardView'
import LetterView from '@/credit/views/county/unionProvince/components/LetterView'
import InfoView from '@/credit/views/city/bus/normal/Info'
import FlowDialog from '@/credit/components/flow/ViewDialog'
import { wfKey } from '@/credit/views/city/self/components/contractApprove/index'

export default {
  components: {
    SelectAddress,
    AttachView,
    AttachCmpt,
    InvestigateApproveView,
    ContractApprove,
    ContractApproveDialog,
    ContractGuardView,
    LetterView,
    InfoView,
    FlowDialog,
  },
  mixins: [baseMixins],
  data() {
    return {
      enumProjectResStatus,
      order: {
        N1is_history: 'asc',
        N2approved_date: 'desc',
      },
      params: {
        index: 1,
        size: 15,
        address_code: '',
        customer_name: '',
        corp_name: '',
        'project_res_status.eq': 2,
        subKey: 'contract_approval.customer_related_id',
      },
      tableData: [],
      tableColumns: [
        ...baseTableColumns,
        { attrs: { label: '合同金额(万元)', prop: 'reply_funds', align: 'center' } },
        { attrs: { label: '合同完成时间', prop: 'contractFinishDate', width: 140 } },
        {
          attrs: { label: '放款银行', prop: 'replyBank', align: 'center' },
          process: v => v || '-',
        },
        // { attrs: { label: '审批模式', prop: 'processLabel', width: 80, align: 'center' } },
        { attrs: { label: '项目经理' }, slot: 'name' },
        { attrs: { label: '待处理人员', prop: 'itemStatusLabel', width: 80, align: 'center' } },
        {
          attrs: { label: '操作', align: 'center', width: 140 },
          operations: [
            {
              content: '合同审批',
              icon: 'fa fa-gavel',
              event: this.handleEdit,
              ifRender: row => row.editEnable,
            },
            // { content: '上传附件', icon: 'fa fa-clipboard', event: this.hanleAttach },
            { content: '查看', icon: 'fa fa-search', event: this.handleView },
          ],
        },
      ],

      authPerson: {},
      riskManager: {},

      editRow: {},
      editVisible: false,
      reportVisible: false,
      relatedData: {},
      attachVisible: false,
      attachRelatedId: '',
      queryId: '',
      active: 'first',
      editQueryId: '',
      editProcess: 0,

      enumStatus: [
        { label: '未处理', value: 0 },
        { label: '已处理', value: 1 },
        { label: '已拒绝', value: 2 },
      ],
      enumParams: {
        0: {
          'confuse_status.neq': 3,
          'contract_approval_status.eq': 0,
        },
        1: {
          'confuse_status.neq': 3,
          'contract_approval_status.gte': 1,
        },
        2: {
          'confuse_status.eq': 3,
          'loan_approval_status.lt': 1,
        },
      },
      selectStatus: '',
      flowVisible: false,
      flowKey: wfKey,
    }
  },
  computed: {
    userId() {
      return this.$store.getters.userId
    },
  },
  watch: {},
  mounted() {},
  created() {
    this.getConData()
  },
  methods: {
    handleFlow() {
      this.flowVisible = true
    },
    getConData(index = 1) {
      this.getData(index)
        .then(() => {
          this.getEntrustContract()
          return getFollow(this.tableData, 'CONTRACT_APPROVAL_DIR')
        })
        .then(follow => {
          this.tableData = this.tableData.map(it => {
            const data = follow.find(item => item.wf_related_id === it.customer_related_id) || {}
            it.itemStatusLabel = +it.confuse_status === 3 ? `已拒绝` : data.innerFollow || ''
            it.editEnable = data.task_person?.includes(this.userId) ?? false
            return it
          })
        })
    },
    async getEntrustContract() {
      if (!this.tableData.length) return
      getEntrustContract(this.tableData).then(list => {
        this.tableData = this.tableData.map(it => {
          const entrust = list[it.customer_related_id] || {}
          it.replyBank = entrust.bank_name || '-'
          it.reply_funds = entrust.reply_funds || '-'
          return it
        })
      })
    },

    handleEdit(row = {}) {
      this.editQueryId = row.customer_related_id
      this.editProcess = +row.process_status
      this.editVisible = true
    },
    dataAdapter(item) {
      item.guaType = enumGuatype[item.gua_type] || '-'
      item.processLabel = enumProcessStatus[item.process_status] || ''

      const approval = item.contract_approval?.[0] || {}
      item.contractFinishDate = this.$utils.dateFormat(approval.res_a_date, this.dateFmt)
      item.itemStatusLabel = ''
      // item.editEnable = getProcessEditable({
      //   approval,
      //   related: item,
      //   authPerson: this.authPerson,
      //   riskManager: this.riskManager
      // })

      return item
    },
    hanleAttach(row) {
      this.attachVisible = true
      this.attachRelatedId = row.customer_related_id
    },
    handleView(row) {
      this.active = 'first'
      this.queryId = row.customer_related_id
      this.relatedData = row
      this.reportVisible = true
    },
    handleSuccess() {
      this.getConData(this.params.index)
      this.$store.dispatch('getTaskCountBusSelf')
    },
    handleStatusChange() {
      const stautsParams = this.enumParams[this.selectStatus] || {}
      const resetParams = Object.keys(this.enumParams).reduce((prev, curr) => {
        for (const key in this.enumParams[curr]) {
          prev[key] = ''
        }
        return prev
      }, {})
      this.params = {
        ...this.params,
        ...resetParams,
        ...stautsParams,
      }
      this.getConData()
    },
  },
}
</script>
<style lang="scss" scoped>
.status-label {
  display: inline-block;
  padding: 0.25em 0.4em;
  font-size: 75%;
  font-weight: 700;
  line-height: 1;
  text-align: center;
  vertical-align: baseline;
  border-radius: 0.25rem;
  transition: color 0.15s;
}
</style>
